package servlet;

import bean.*;
import service.impl.OrderItemServiceImpl;
import service.impl.OrderServiceImpl;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@WebServlet("/user/order")
public class AddOrderServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        OrderItemServiceImpl orderItemService = new OrderItemServiceImpl();
        OrderServiceImpl orderService = new OrderServiceImpl();
        User user = (User)request.getSession().getAttribute("user");
        if(user==null){
            request.getRequestDispatcher("login.jsp").forward(request,response);
        }else {
            ScreeningSchedule screeningSchedule = (ScreeningSchedule)request.getSession().getAttribute("screeningSchedule");
            System.out.println(screeningSchedule);
            Movie movie = (Movie) request.getSession().getAttribute("movie");


            // 获取表单参数
            String selectedSeatsStr = request.getParameter("selectedSeats");

            // 将逗号分隔的字符串转换为 List<String>
            List<String> selectedSeats = Arrays.asList(selectedSeatsStr.split(","));
            int selectedSeatNum =  selectedSeats.size();
            BigDecimal total = movie.getPrice().multiply(BigDecimal.valueOf(selectedSeatNum));
            Order order = new Order();
            order.setOrderDate(new Date(System.currentTimeMillis()));
            order.setUser(user);
            order.setTotal(total);
            order.setScreeningSchedule(screeningSchedule);
            int orderId = orderService.addOrder(order);
            // 处理选中的座位（例如，存储到数据库）
            // 这里简单打印出选中的座位
            for (String seat : selectedSeats) {
                System.out.println("Selected seat: " + seat);
                OrderItem orderItem = new OrderItem();
                orderItem.setOrderId(orderId);
                orderItem.setPrice(movie.getPrice());
                orderItem.setSeat(seat);
                orderItemService.addOrderItem(orderItem);
            }
            request.setAttribute("message","预定成功，支付成功");
            request.setAttribute("page","index.jsp");
            request.getRequestDispatcher("alert.jsp").forward(request,response);
        }


    }
}
